package com.deshan.websys.api.config;




import com.deshan.websys.api.utils.CachUtil;
import com.deshan.websys.code.model.PmsIm;
import com.deshan.websys.code.service.PmsImService;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/chatWs/{fromuserid}/to/{touserid}")
@Component
public class WebSocketServerImpl {
        //线程安全的map，用来保存每个客户端对应的WebSocket对象
        private static ConcurrentHashMap<String, WebSocketServerImpl> webSocketMap = new ConcurrentHashMap<>();
        private static ConcurrentHashMap<String, LinkedHashMap> messageMap = new ConcurrentHashMap<>();
        //单个客户端的session，通过session与对应客户端通讯
        private Session session;
        //用户id
        private String fromuserId;
        private String touserid;
        @Resource
        ApplicationContextProvider applicationContextProvider;





        /**
         * 连接成功
         * @OnOpen注解：websocket 连接成功后，触发该注解修饰的方法
         * @param session
         */
        @OnOpen
        public void onOpen(Session session, @PathParam("fromuserid") String fromuserid, @PathParam("touserid") String touserid) {
            this.session = session;
            this.fromuserId = fromuserid;
            this.touserid=touserid;
            if (webSocketMap.containsKey(fromuserid)) {
                webSocketMap.remove(fromuserid);
                webSocketMap.put(fromuserid, this);
            } else {
                webSocketMap.put(fromuserid, this);
            }
            System.out.println("连接成功");
            LinkedHashMap<String,PmsIm>  usermap= messageMap.get(fromuserid);
            if(usermap!=null){
                Iterator it=usermap.keySet().iterator();
                while(it.hasNext()){
                    Object key=it.next();
                    PmsIm pmsIm = usermap.get(key);
                    try {
                        sendInfo(fromuserId,pmsIm.getContent());
//                    webSocketMap.get(fromuserId).session.getBasicRemote().sendText(text);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                usermap.clear();
            }

        }

        /**
         * 连接关闭
         * @OnClose注解：websocket断开连接后，触发该注解修饰的方法
         * @param session
         */
        @OnClose
        public void onCLose(Session session) {
            if (webSocketMap.containsKey(fromuserId)) {
                webSocketMap.remove(fromuserId);
            }
            System.out.println("关闭连接");
        }

        /**
         * 接收消息
         * @OnMessage注解：客户端发送消息时，触发该注解声明的方法
         * @param text
         * @return
         */
        @OnMessage
        public void onMessage(String text) {
            System.out.println("后端接收前端web发送数据userId:" + fromuserId + ",接收信息：" + text);
            PmsIm pmsIm=new PmsIm();
            pmsIm.setFromMemberid(fromuserId);
            pmsIm.setToMemberid(touserid);
            pmsIm.setContent(text);
            pmsIm.setCreateTime(Calendar.getInstance().getTime());
            if (webSocketMap.containsKey(touserid)) {
                try {
                    sendInfo(touserid,text);
//                    webSocketMap.get(fromuserId).session.getBasicRemote().sendText(text);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
               LinkedHashMap<String,PmsIm>  usermap= messageMap.get(touserid);
               if(usermap==null){
                   usermap=new LinkedHashMap<>();
                   usermap.put(String.valueOf(System.currentTimeMillis()),pmsIm);
                   messageMap.put(touserid,usermap);
               }else{
                   usermap.put(String.valueOf(System.currentTimeMillis()),pmsIm);
                   messageMap.put(touserid,usermap);
               }
            }
            savePmsIm(pmsIm);
        }

        /**
         * 连接异常
         * @OnError注解：当建立的连接出现异常后，触发该注解修饰的方法
         * @param session
         * @param throwable
         */
        @OnError
        public void onError(Session session, Throwable throwable) {
            System.out.println("websocket连接异常：" + throwable.getMessage());
        }

        /**
         * 服务器给指定WebSocket客户端发送信息
         * @param touserid
         * @param message
         */
        public static void sendInfo(String touserid, String message) {
            System.out.println("后端发送前端web数据userId:" + touserid + "发送消息：" + message);
            if (webSocketMap.containsKey(touserid)) {
                try {
//                    webSocketMap.get(userId).session.getBasicRemote().sendText("后端发送前端web数据userId" + userId + "，内容：" + message);
                    webSocketMap.get(touserid).session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        public void savePmsIm(PmsIm pmsIm){
            try {
                ApplicationContext applicationContext = applicationContextProvider.getApplicationContext();
//                PmsImService pmsImService = (PmsImService) applicationContext.getBean("pmsImService");
                PmsImService pmsImService = applicationContext.getBean(PmsImService.class);
                pmsImService.saveImData(pmsIm);
            }catch (Exception e){

                System.out.println(e.getMessage());
            }

        }



}
